<?php
/**
  * 
  * @author wanghch
  * @email wanghch@mediav.com
  * @date Apr 18, 2013
  * express checkout
  */
define('PP_CONFIG_PATH',Yii::getPathOfAlias("application.extensions.merchant-sdk").'/config/');
require_once Yii::getPathOfAlias("application.extensions.merchant-sdk").'/vendor/autoload.php';


class PaypalController extends CController{
	public function actionIndex()
	{
		$this->render('index');	
	}
	
	/**
	 * set express checkout
	 * @author wanghch
	 * @email wanghch@mediav.com
	 * @date Apr 18, 2013
	 */
	public function actionSetEc($orderid){
		$cusomerId = Yii::app()->user->id;
		$order = Order::model()->findByPk($orderid);
		$orderMap = OrderProductMap::model()->with('product')->findAllByAttributes(array('orderid'=>$orderid,'customerid'=>$cusomerId));
		
		$paymentDetails = new PaymentDetailsType();
		$itemTotalValue = $order->amount;
		$currencyCode = $order->currency;
		$i = 0;
		$currencyCode = 'USD';
		foreach($orderMap as $cm){
			$itemAmount = new BasicAmountType($cm->currency, $cm->amount);
			$itemDetails = new PaymentDetailsItemType();
			$itemDetails->Amount = $itemAmount;
			$itemDetails->Name = $cm->product->name;
			$itemDetails->Quantity = $cm->num;
			$itemDetails->ItemCategory = 'Physical';
			//$itemDetails->Tax = new BasicAmountType($currencyCode, $_REQUEST['itemSalesTax'][$i]);
			
			$paymentDetails->PaymentDetailsItem[$i++] = $itemDetails;
		}
// 		
// 		$shippingTotalAmount = 0;
// 		$handlingTotalAmount = 0;
// 		$insuranceTotalAmount = 0;
		
// 		$shippingTotal = new BasicAmountType($currencyCode, $shippingTotalAmount);
// 		$handlingTotal = new BasicAmountType($currencyCode, $handlingTotalAmount);
// 		$insuranceTotal = new BasicAmountType($currencyCode, $insuranceTotalAmount);
		
		$address = new AddressType();
		$userid = Yii::app()->user->id;
		
		$addressModel = Address::model()->findByPk($userid);
		if($addressModel){
			$address->CityName = $addressModel->city;
			$address->Name = $addressModel->user->username;
			$address->Street1 = $addressModel->street;
			$address->StateOrProvince = $addressModel->province;
			$address->PostalCode = $addressModel->postal_code;
			$address->Country = $addressModel->country_code;
			$address->Phone = $addressModel->phone;
			$paymentDetails->ShipToAddress = $address;
		}
		
// 		$orderTotalValue = $shippingTotal->value + $handlingTotal->value +
// 		$insuranceTotal->value +
// 		$itemTotalValue + $taxTotalValue;
		
		
		$orderTotalValue = $itemTotalValue;
		
		
		
		$paymentDetails->ItemTotal = new BasicAmountType($currencyCode, $itemTotalValue);
		$paymentDetails->OrderTotal = new BasicAmountType($currencyCode, $orderTotalValue);
// 		$paymentDetails->TaxTotal = new BasicAmountType($currencyCode, $taxTotalValue);
		$paymentDetails->PaymentAction = 'Sale';
		
// 		$paymentDetails->HandlingTotal = $handlingTotal;
// 		$paymentDetails->InsuranceTotal = $insuranceTotal;
// 		$paymentDetails->ShippingTotal = $shippingTotal;
		
		//$paymentDetails->NotifyURL = $_REQUEST['notifyURL'];
		
		$setECReqDetails = new SetExpressCheckoutRequestDetailsType();
		$setECReqDetails->PaymentDetails[0] = $paymentDetails;
		
		
		// Shipping details
// 		$setECReqDetails->NoShipping = $_REQUEST['noShipping'];
		$setECReqDetails->AddressOverride = 0;
// 		$setECReqDetails->ReqConfirmShipping = $_REQUEST['reqConfirmShipping'];
		
		// Billing agreement
// 		$billingAgreementDetails = new BillingAgreementDetailsType($_REQUEST['billingType']);
// 		$billingAgreementDetails->BillingAgreementDescription = $_REQUEST['billingAgreementText'];
// 		$setECReqDetails->BillingAgreementDetails = array($billingAgreementDetails);
		
		// Display options
		
// 		$setECReqDetails->cppheaderimage = $_REQUEST['cppheaderimage'];
// 		$setECReqDetails->cppheaderbordercolor = $_REQUEST['cppheaderbordercolor'];
// 		$setECReqDetails->cppheaderbackcolor = $_REQUEST['cppheaderbackcolor'];
// 		$setECReqDetails->cpppayflowcolor = $_REQUEST['cpppayflowcolor'];
// 		$setECReqDetails->cppcartbordercolor = $_REQUEST['cppcartbordercolor'];
// 		$setECReqDetails->cpplogoimage = $_REQUEST['cpplogoimage'];
// 		$setECReqDetails->PageStyle = $_REQUEST['pageStyle'];
// 		$setECReqDetails->BrandName = $_REQUEST['brandName'];
		
		// Advanced options
		$setECReqDetails->AllowNote = 0;
		
		$returnUrl = $this->createAbsoluteUrl('/pay/paypal/getEc',array('id'=>$order->id));
		$cancelUrl = $this->createAbsoluteUrl('/pay/paypal/cancel',array('id'=>$order->id));
		$setECReqDetails->CancelURL = $cancelUrl;
		$setECReqDetails->ReturnURL = $returnUrl;

		
		$setECReqType = new SetExpressCheckoutRequestType();
		$setECReqType->SetExpressCheckoutRequestDetails = $setECReqDetails;
		$setECReq = new SetExpressCheckoutReq();
		$setECReq->SetExpressCheckoutRequest = $setECReqType;
		
		$paypalService = new PayPalAPIInterfaceServiceService();
		try {
			/* wrap API method calls on the service object with a try catch */
			$setECResponse = $paypalService->SetExpressCheckout($setECReq);
		} catch (Exception $ex) {
			$this->render('error',array('ex'=>$ex));
			exit;
		}
		if(isset($setECResponse)) {
			Yii::log(print_r($setECResponse,true),CLogger::LEVEL_INFO,'pay.paypal');
			if($setECResponse->Ack =='Success') {
				$token = $setECResponse->Token;
				$paypalModel = new Paypal();
				$paypalModel->paymentid =  $token;
				$paypalModel->payment_method = 'express';
				$paypalModel->create_time = date('Y-m-d H:i:s');
				$paypalModel->amount_currency = $currencyCode;
				$paypalModel->amount_total = $orderTotalValue;
				$paypalModel->state = 0;
				$paypalModel->orderid = $order->id;
				if($paypalModel->save()){
					$orderPay = new OrderPay();
					$orderPay->orderid = $order->id;
					$orderPay->payid = $paypalModel->id;
					$orderPay->pay_type = OrderPay::PAYPAL;
					$orderPay->paytime = date('Y-m-d H:i:s');
					if($orderPay->save()){
						$payPalURL = 'https://www.sandbox.paypal.com/webscr?cmd=_express-checkout&token=' . $token;
						$this->redirect($payPalURL);
					}else{
						echo "pay save failed";
						echo print_r($orderPay->getErrors(),true);
					}
				}else{
					echo "pay save failed";
					echo print_r($paypalModel->getErrors(),true);
				}
			}else{
				$this->render('error',array('setECResponse'=>$setECResponse));
				exit;
			}
		}
	}
	public function actionMsg(){
		$this->render('error');
	}
	public function actionDoEc($payid){
		$payment = Paypal::model()->findByPk($payid);
		$token =urlencode( $payment->paymentid);
		$payerId=urlencode( $payment->payerid);
		$paymentAction = urlencode('Sale');
		$getExpressCheckoutDetailsRequest = new GetExpressCheckoutDetailsRequestType($token);
		$getExpressCheckoutReq = new GetExpressCheckoutDetailsReq();
		$getExpressCheckoutReq->GetExpressCheckoutDetailsRequest = $getExpressCheckoutDetailsRequest;
		
		$paypalService = new PayPalAPIInterfaceServiceService();
		try {
			/* wrap API method calls on the service object with a try catch */
			$getECResponse = $paypalService->GetExpressCheckoutDetails($getExpressCheckoutReq);
		} catch (Exception $ex) {
			$this->render('error',array('ex'=>$ex));
			exit;
		}
		//----------------------------------------------------------------------------
		
		$orderTotal = new BasicAmountType();
		$orderTotal->currencyID = $payment->amount_currency;
		$orderTotal->value = $payment->amount_total;
		
		$paymentDetails= new PaymentDetailsType();
		$paymentDetails->OrderTotal = $orderTotal;
		if(isset($_REQUEST['notifyURL']))
		{
			$paymentDetails->NotifyURL = $_REQUEST['notifyURL'];
		}
		
		$DoECRequestDetails = new DoExpressCheckoutPaymentRequestDetailsType();
		$DoECRequestDetails->PayerID = $payerId;
		$DoECRequestDetails->Token = $token;
		$DoECRequestDetails->PaymentAction = $paymentAction;
		$DoECRequestDetails->PaymentDetails[0] = $paymentDetails;
		
		$DoECRequest = new DoExpressCheckoutPaymentRequestType();
		$DoECRequest->DoExpressCheckoutPaymentRequestDetails = $DoECRequestDetails;
		
		
		$DoECReq = new DoExpressCheckoutPaymentReq();
		$DoECReq->DoExpressCheckoutPaymentRequest = $DoECRequest;
		
		try {
			$DoECResponse = $paypalService->DoExpressCheckoutPayment($DoECReq);
		} catch (Exception $ex) {
			$this->render('error',array('ex'=>$ex));
			exit;
		}
		if(isset($DoECResponse)) {
// 			echo "<table>";
// 			echo "<tr><td>Ack :</td><td><div id='Ack'>$DoECResponse->Ack</div> </td></tr>";
// 			if(isset($DoECResponse->DoExpressCheckoutPaymentResponseDetails->PaymentInfo)) {
// 				echo "<tr><td>TransactionID :</td><td><div id='TransactionID'>". $DoECResponse->DoExpressCheckoutPaymentResponseDetails->PaymentInfo[0]->TransactionID."</div> </td></tr>";
// 			}
// 			echo "</table>";
// 			echo "<pre>";
// 			print_r($DoECResponse);
// 			echo "</pre>";
			
			
			if($DoECResponse->Ack == 'Success'){
				$payment->state = 3;
				if($payment->update(array('finishtime','state'))){
					if(Order::model()->updateByPk($payment->orderid, array('status'=>3,'finishtime'=>Utils::utc2LocalDatetime($DoECResponse->Timestamp)))){
						
					}
				}else{
					Yii::log(print_r($payment->getErrors(),true),'error');
				}
			}
			$this->redirect( $this->createUrl('/pay/order/detail',array('orderid'=>$payment->orderid)));
		}
		
	}
	
	public function actionGetEc($id){
		session_start();
		
		$token = $_REQUEST['token'];
		
		$getExpressCheckoutDetailsRequest = new GetExpressCheckoutDetailsRequestType($token);
		
		$getExpressCheckoutReq = new GetExpressCheckoutDetailsReq();
		$getExpressCheckoutReq->GetExpressCheckoutDetailsRequest = $getExpressCheckoutDetailsRequest;
		
		$paypalService = new PayPalAPIInterfaceServiceService();
		try {
			$getECResponse = $paypalService->GetExpressCheckoutDetails($getExpressCheckoutReq);
		} catch (Exception $ex) {
			$this->render('error',array('ex'=>$ex));
			exit;
		}
		if(isset($getECResponse)) {
			$paymentModel = Paypal::model()->findByAttributes(array('paymentid'=>$token));

			$payTime = Utils::utc2LocalDatetime($getECResponse->Timestamp);
			
			$ecDetail = $getECResponse->GetExpressCheckoutDetailsResponseDetails;
			$payerName = $getECResponse->GetExpressCheckoutDetailsResponseDetails->PayerInfo->PayerName->FirstName.
			$getECResponse->GetExpressCheckoutDetailsResponseDetails->PayerInfo->PayerName->LastName;
// 			$paymentModel->paymentid = $token;
// 			$paymentModel->create_time = date('Y-m-d H:i:s');
			$paymentModel->state = 2;
// 			$paymentModel->payment_method = 'express';
			$paymentModel->orderid = $id;
			$paymentModel->email = $getECResponse->GetExpressCheckoutDetailsResponseDetails->PayerInfo->Payer;
			$paymentModel->payername = $payerName;
			$paymentModel->payerid = $getECResponse->GetExpressCheckoutDetailsResponseDetails->PayerInfo->PayerID;
// 			$paymentModel->amount_total = $ecDetail->PaymentDetails[0]->OrderTotal->value;
// 			$paymentModel->amount_currency = $ecDetail->PaymentDetails[0]->OrderTotal->currencyID;
// 			$paymentModel->update_time = $payTime;
			
			if($paymentModel->update(array('email','orderid','payername','payerid'))){
				$url = $this->createUrl('/pay/paypal/doEc',array('payid'=>$paymentModel->id));
				$this->render('confirmPay',array('url'=>$url,'getECResponse'=>$getECResponse));
// 				$orderModel = Order::model()->findByPk($paymentModel->orderid);
// 				$orderModel->status = Order::FINISHED;
// 				$orderModel->paytime = $paymentModel->create_time;
// 				$orderModel->finishtime = $payTime;
// 				if($orderModel->update(array('status','paytime','finishtime'))){
							
// 				}else{
// 					print_r($orderModel->getErrors());
// 				}
			}else{
// 				print_r($paymentModel->getErrors());
			}
			
			
			Yii::log($id.print_r($getECResponse,true),CLogger::LEVEL_INFO,'pay.paypal');
		}	
	}
	
	public function actionCancel(){
		Yii::log('paypal cancel'.print_r($_REQUEST,true),CLogger::LEVEL_INFO,'pay.paypal');
		$this->redirect('/pay/default/cart');
	}
}